﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace psafth.FSR.Lapcounter
{
    public class MulticastThread : BackgroundWorker
    {
        private Queue<QueueObject> _queue;

        private IPAddress _multicastAddress;
        private UdpClient _udpClient;
        private IPEndPoint _remoteEndPoint;
        private int _port;
        private bool _run;

        public MulticastThread(string multicastAdress, int port)
        {
            _multicastAddress = IPAddress.Parse(multicastAdress);
            _udpClient = new UdpClient();
            _port = port;
            _queue = new Queue<QueueObject>();
            _run = true;
        } 

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            _udpClient.JoinMulticastGroup(_multicastAddress);
            _remoteEndPoint = new IPEndPoint(_multicastAddress, _port);

            while(_run){

                if (_queue.Count > 0)
                {
                    QueueObject toSend = _queue.Dequeue();

                    if (toSend != null)
                    {
                        byte[] bytesToSend = MulticastHelper.ObjectToByteArray(toSend.Object, (byte)toSend.Type);
                        _udpClient.Send(bytesToSend, bytesToSend.Length, _remoteEndPoint);
                    }
                }
            }

            base.OnDoWork(e);
        }

        public void Send(object obj, MulticastDataType t)
        {
            _queue.Enqueue(new QueueObject(){ Object = obj, Type = t});
        }
    }

    class QueueObject
    {
        public object Object
        {
            get;
            set;
        }

        public MulticastDataType Type
        {
            get;
            set;
        }

        public QueueObject()
        {
        }
    }
}
